`
we wanted to change this script so that we first check that we have
enough space on the disk before attempting to create new files and
directories? Or what if we checked whether the directory and file
creation actions actually succeeded? This section and the next
chapter introduce you to the syntactical elements you’ll need to
accomplish these tasks.
Variables
Every scripting language has variables. Variables are names we
assign to memory locations that hold some value, and they act like
placeholders or labels. We can directly assign values to variables or
execute bash commands and store their output as variable values to
use for various purposes.
If you’ve worked with programming languages, you may know
that variables can be of different types, such as integers, strings, and
arrays. In bash, variables are untyped; they’re all considered
character strings. Even so, you’ll see that bash allows you to create
arrays, access array elements, or perform arithmetic operations so
long as the variable value consists of only numbers.
The following rules govern the naming of bash variables:
• They can include alphanumeric characters.
• They cannot start with a numerical character.
• They can contain an underscore (_).
• They cannot contain whitespace.
Assigning and Accessing Variables
Let’s assign a variable. Open a terminal and enter the following
directly in the command prompt:
$ book="black hat bash"
We create a variable named book, and by using the equal sign
(=), assign the value black hat bash to it. Now we can use this
variable in some command. For example, here we use the echo
command to print the variable to the screen:
$ echo "This book's name is ${book}"
This book's name is black hat bash
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks